import 'package:rxdart/rxdart.dart';
import 'package:wuxu_flutter_lianxi/dao/UserDao.dart';
import 'package:wuxu_flutter_lianxi/model/user.dart';
import 'package:wuxu_flutter_lianxi/redux/wx_state.dart';

import 'package:redux/redux.dart';

import 'middleware/epic_store.dart';


///
/// 用户Redux
///
/// 登录Redux中已经维护了用户信息，这个redux废弃
///


///
/// action
///
class UpdateUserAction{
  UserInfo? user;
  UpdateUserAction(this.user);
}

class FetchUserAction {}

///TypedReducer 是个处理action类型的工具类
///下面这个代码：使用TypeReducer 过滤出 action == UpdateUserAction 并交给_updateLoaded函数
final UserReducer = TypedReducer<UserInfo?,UpdateUserAction>(_updateLoaded);

UserInfo? _updateLoaded(UserInfo? user,action){
  user = action.user;//action 其实是 UpdateUserAction类型
  return user;
}

///
/// middleware 中间件
///

/// 这个中间件只是为了打印下日志，没有实际用途
class UserInfoMiddleware implements MiddlewareClass<WXState> {
  @override
  void call(Store<WXState> store, dynamic action, NextDispatcher next) {
    if (action is UpdateUserAction) {
      print("*********** UserInfoMiddleware *********** ");
    }
    //这一步可以看出，Redux采用了责任链设计模式，将action传递给下一个中间件
    next(action);
  }
}

///
/// 设定异步中间件EpicMiddleware 的方法，加载用户信息
///
/// 使用Stream进行异步请求
///
Stream<dynamic> epicLoadUserInfo(Stream<dynamic> actions,EpicStore<WXState> store){

    Stream<dynamic> _loadUserInfo() async*{//async* 返回Stream，标记此函数是异步迭代器函数
      var res= await UserDao.getUserInfo();
      yield UpdateUserAction(res);
    }

    return actions
        .whereType<FetchUserAction>()//过滤action
        .debounce(((_) => TimerStream(true, const Duration(milliseconds: 10))))//防重，延迟启动，如果有多次事件只执行最后一次
        .switchMap((action) => _loadUserInfo());
}